package com.example.swordkotlin

import java.util.*

object Test7 {

    @JvmStatic
    fun main(args: Array<String>) {
        val pre = intArrayOf(1, 2, 4, 7, 3, 5, 6, 8)
        val vin = intArrayOf(4, 7, 2, 1, 5, 3, 8, 6)
        reConstructBinaryTree(pre, vin)
    }

    class TreeNode(var `val`: Int, var left: TreeNode? = null, var right: TreeNode? = null)


    /**
     * 给定节点数为 n 的二叉树的前序遍历和中序遍历结果，请重建出该二叉树并返回它的头结点。
     * 例如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6}，
     * */

    private fun reConstructBinaryTree(preOrder: IntArray, vinOrder: IntArray): TreeNode? {
        // write code here
        var root: TreeNode? = null
        for (i in preOrder.indices) {
            if (preOrder[0] == vinOrder[i]) {
                root = TreeNode(preOrder[0])
                root.left = reConstructBinaryTree(
                    preOrder.copyOfRange(1, i + 1),
                    vinOrder.copyOfRange(0, i)
                )
                root.right = reConstructBinaryTree(
                    preOrder.copyOfRange(i + 1, preOrder.size),
                    vinOrder.copyOfRange(i + 1, vinOrder.size)
                )
            }
        }
        return root
    }
}